//
//  NewsListController.m
//  easystudy
//
//  Created by kane on 15/6/1.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "NewsListController.h"
#import "CityViewController.h"
#import "SearchViewController.h"
#import "MessageViewController.h"
#import "MJRefresh.h"
#import "NewsListCell.h"
#import "ChannelManageViewController.h"
#import "SearchSubjectViewController.h"
#import "ContentViewController.h"
#import "FilterContentView.h"

@interface NewsListController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,MJRefreshBaseViewDelegate,NewsListCellDelegate,ContentViewDelegate>
{
    __weak IBOutlet UILabel *titleLbl;
    __weak IBOutlet UIButton *refreshBtn;
    __weak IBOutlet UITableView *dataTable;
    NSMutableArray *dataList;
    
    MJRefreshHeaderView *header;

    EmptyView *emptyView;
    FilterContentView *_filterView;
    NSTimer *timer;
}

@end

@implementation NewsListController
@synthesize dataInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
     dataList = [NSMutableArray array];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initUI];
    [self initRefreshUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    [self changeNightMode];
    [header beginRefreshing];
    
}

-(void)changeNightMode
{
    self.view.backgroundColor = IS_NightMode?[UIColor blackColor]:[UIColor whiteColor];
}

- (void)initUI
{
    titleLbl.text = [dataInfo[@"channel_name"] convertToString];
    titleLbl.frame = CGRectMake(130, 30, 120, 30);
    [titleLbl sizeToFit];
    refreshBtn.frame = CGRectMake(titleLbl.maxX , titleLbl.minY-7, 30, 30);
    
}



- (void)refreshBtnRevolve
{
    static float angle = 0;
    angle -= 5;
    refreshBtn.transform = CGAffineTransformMakeRotation(angle * M_PI / 180.0f);
    if (angle < -540) {
        [timer invalidate];
        angle = 0;
    }
}

- (void)initRefreshUI
{
    header = [MJRefreshHeaderView header];
    header.scrollView = dataTable;
    header.delegate = self;
    refreshBtn.transform = CGAffineTransformMakeRotation( M_PI / 180.0f);
    [header beginRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"a_channelid":[dataInfo[@"channel_id"] convertToString],@"a_status":@""};
    [WebService findArticleList:params WithBlock:^(id result, NSError *error) {
//        [timer invalidate];
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"article"][@"value"];
                [dataList removeAllObjects];
                [dataList addObjectsFromArray:dataAry];
                [dataTable reloadData];
            }
        }
        [refreshView endRefreshing];
    }];
}



#pragma mark -userAction
- (IBAction)backBtnPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)refreshBtnClick:(UIButton *)sender {
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.007 target:self selector:@selector(refreshBtnRevolve) userInfo:nil repeats:YES];
    [self initRefreshUI];
}



#pragma mark - UITableView DataSource && Delegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = dataList[indexPath.row];
    NSString *imgString = [item[@"a_picture"] convertToString];
    NSArray *photoAry = [imgString componentsSeparatedByString:@","];
    NSInteger type = 0;
    if (photoAry.count >= 3) {
        type = 3;
    }else if (photoAry.count >= 1){
        type = 1;
    }
    switch (type) {
        case 0:
            return 85;
            break;
        case 1:
            return 90;
            break;
        case 3:
            return 170;
            break;
        default:
            break;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"HomeClassCell";
    NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.dataIndex = indexPath.row;
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dict = dataList[indexPath.row];
    [cell setupNewsData:dict];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = dataList[indexPath.row];
    ContentViewController *contentVC = [[ContentViewController alloc] init];
    contentVC.dataInfo = item;
    contentVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contentVC animated:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    SearchSubjectViewController *subVC = [[SearchSubjectViewController alloc] init];
//    SearchViewController *searchVC = [[SearchViewController alloc] init];
    subVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:subVC animated:YES];
    return NO;
}
#pragma mark - NewListCellDelegate
- (void)clickFilterButton:(NSInteger)index withCGRect:(CGRect)rect
{
    if(!_filterView){
        _filterView = [[[UINib nibWithNibName:@"FilterContentView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
        _filterView.frame = CGRectMake(0, 0, fWidth_Current, fHeight_Current);
        [_filterView.contentView drawCornerRadius:5];
        _filterView.dataIndex = index;
        _filterView.delegate = self;
        [self drawButtonWithBtn:_filterView.titleBtn];
        [self drawButtonWithBtn:_filterView.contentBtn];
        [self drawButtonWithBtn:_filterView.sourceBtn];
        [self drawButtonWithBtn:_filterView.channelBtn];
        [self drawButtonWithBtn:_filterView.typeBtn1];
        [self drawButtonWithBtn:_filterView.typeBtn2];
    }
    if (rect.origin.y < fHeight_Current/2) {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y+30,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_up"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y+15,80,60};

    }else {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y - _filterView.contentView.size.height ,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_down"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y-45,80,60};
    }
    [self.view addSubview:_filterView];
}
- (void)drawButtonWithBtn:(UIButton *)button
{
    [button drawCornerRadius:15];
    [button drawBorderColor:[UIColor lightGrayColor] Width:0.5];
}

#pragma mark - ContentViewDelegate
- (void)clickShieldButton:(NSInteger)index
{
    //点击 不感兴趣(确认屏蔽) 按钮
    
}



@end
